package io.renren.modules.courseTest.controller;

import com.alibaba.fastjson.JSONArray;
import com.google.gson.reflect.TypeToken;
import io.renren.common.annotation.Login;
import io.renren.common.config.ListPageUtils;
import io.renren.common.config.SensitiveWordFilter;
import io.renren.common.utils.R;
import io.renren.modules.courseTest.entity.ChooseTestCommentEntity;
import io.renren.modules.courseTest.entity.ChooseTestEntity;
import io.renren.modules.courseTest.entity.UserChooseTestInfo;
import io.renren.modules.courseTest.service.courseTestService;
import io.renren.modules.sys.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.*;


@RestController
@RequestMapping("api/courseTest")
public class courseTestController {

    @Autowired
    courseTestService courseTestService;
@Autowired
    TokenService tokenService;




    /**
     * 过滤敏感字符
     *
     * @param str
     */
    public String wordFilter(@RequestBody String str) {
        SensitiveWordFilter sw = new SensitiveWordFilter();
        sw.InitializationWork();
        long startNumer = System.currentTimeMillis();
        System.out.println("被检测字符长度:" + str.length());
        str = sw.filterInfo(str);
        long endNumber = System.currentTimeMillis();
        System.out.println("耗时(毫秒):" + (endNumber - startNumer));
        System.out.println("过滤之后:" + str);
        return str;
    }

    /**
     * 获取这个课程的这一章的这一节的测试题的id
     */
    @PostMapping("getCourseTestIdList")
    public R getCourseTestIdList(@RequestBody Map map){
        /*int courseId = Integer.valueOf(map.get("courseId").toString());
        int chapterId = Integer.valueOf(map.get("chapterId").toString());
        int sectionId = Integer.valueOf(map.get("sectionId").toString());*/

        List ids = courseTestService.getCourseTestIdList(map);
        return R.ok("success",100).put("data",ids);
    }

    /**
     * 查询一条测试题
     */
    @PostMapping("getOneCourseTest")
    @Login
    public R getOneCourseTest(@RequestBody Map map){
        int id = Integer.valueOf(map.get("id").toString());

        ChooseTestEntity c =  courseTestService.getOneCourseTest(id);
        //c.setAnswer(null);
        if("".equals(c.getOptionOneImg()) || "无".equals(c.getOptionOneImg())){
            c.setOptionOneImg("");
        }
        if("".equals(c.getOptionTwoImg()) || "无".equals(c.getOptionTwoImg())){
            c.setOptionTwoImg(null);
        }
        if("".equals(c.getOptionThreeImg()) || "无".equals(c.getOptionThreeImg())){
            c.setOptionThreeImg(null);
        }
        if("".equals(c.getOptionFourImg()) || "无".equals(c.getOptionFourImg())){
            c.setOptionFourImg(null);
        }
        /*if("无".equals(c.getQuestionContent())){
            c.setQuestionContent(null);
        }
        if("无".equals(c.getOptionOne())){
            c.setOptionOne(null);
        }
        if("无".equals(c.getOptionTwo())){
            c.setOptionTwo(null);
        }
        if("无".equals(c.getOptionThree())){
            c.setOptionThree(null);
        }
        if("无".equals(c.getOptionFour())){
            c.setOptionFour(null);
        }*/
        return R.ok("success",100).put("data",c);
    }


    /**
     * 获取所有测试题
     */
    @PostMapping("getAllCourseTest")
    @Login
    public R getAllCourseTest(@RequestBody Map map){

        List list = courseTestService.getAllCourseTest(map);
        for(int i =0;i<list.size();i++){
            ChooseTestEntity c = (ChooseTestEntity)list.get(i);
            c.setAnswer(null);
            /*if("".equals(c.getOptionOneImg()) || "无".equals(c.getOptionOneImg())){
                    c.setOptionOneImg(null);
                }
                if("".equals(c.getOptionTwoImg()) || "无".equals(c.getOptionTwoImg())){
                    c.setOptionTwoImg(null);
                }
                if("".equals(c.getOptionThreeImg()) || "无".equals(c.getOptionThreeImg())){
                    c.setOptionThreeImg(null);
                }
                if("".equals(c.getOptionFourImg()) || "无".equals(c.getOptionFourImg())){
                    c.setOptionFourImg(null);
            }*/

        }
       return R.ok("success",100).put("data",list);
    }

    /**
     * 测试传来的答案是否正确
     */
    @PostMapping("checkAnswer")
    @Login
    public R checkAnswer(@RequestBody ChooseTestEntity chooseTestEntity){
        String answerStr = chooseTestEntity.getAnswerList();
        int userId = Integer.valueOf(tokenService.getUserIdByToken(chooseTestEntity.getToken()).toString());  //用户id
        String newAnswerStr = answerStr.replace("[","");
        String newNewAnswerStr = newAnswerStr.replace("]","");
        //前台传来的答案列表
        List answerList =  Arrays.asList(newNewAnswerStr.split(","));
        int score = 0;
        List errorList = new ArrayList();  //记录错误的题号
        List trueList = new ArrayList();  //记录正确的题号

        Map map = new HashMap();
        map.put("courseId",chooseTestEntity.getCourseId());
        map.put("courseBodyId",chooseTestEntity.getCourseBodyId());
        map.put("userId",userId);
        List courseTestEntityList = courseTestService.getAllCourseTest(map);
        for(int i = 0 ;i<courseTestEntityList.size();i++){
            //获取当前题学生提交的答案
            String studentAnswer = answerList.get(i).toString().trim();
            //获取当前题目信息
            ChooseTestEntity c = (ChooseTestEntity)courseTestEntityList.get(i);
            //通过id获取答案和分数
            String answer = c.getAnswer();
            int testScore = c.getFraction();
            if(studentAnswer.equals(answer)){
                score += testScore;    //获取分数
                trueList.add(i+1);  //记录正确的题号
                c.setTrueOrFalse(1);  //答案是正确的
            }else{
                //答案错误  记录错误的题的题号
                errorList.add(i+1);
                c.setTrueOrFalse(2);  //答案是错误的
            }
        }

        //进行用户和测试题目之间的关系操作
        //首先要获取一次这个用户及这个题目的信息 看是否存在
        UserChooseTestInfo userChooseTestInfoo = getUserChooseTestInfo(map);
        int courseBodyId =chooseTestEntity.getCourseBodyId();   //所属讲的id

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
        if(userChooseTestInfoo == null){
            //添加一条做题记录
            UserChooseTestInfo userChooseTestInfo = new UserChooseTestInfo();
            userChooseTestInfo.setUserId(userId);
            userChooseTestInfo.setCourseBodyId(courseBodyId);
            userChooseTestInfo.setSubmitCount(1);
            userChooseTestInfo.setSubmitEndTime(new Date());//提交时间
            System.out.println(new Date());
            userChooseTestInfo.setTestScore(score);
            addUserChooseTestInfo(userChooseTestInfo);
        }else{
            //修改成现在的记录
            UserChooseTestInfo userChooseTestInfo = new UserChooseTestInfo();
            userChooseTestInfo.setUserId(userChooseTestInfoo.getUserId());
            userChooseTestInfo.setCourseBodyId(userChooseTestInfoo.getCourseBodyId());
            userChooseTestInfo.setSubmitCount(userChooseTestInfoo.getSubmitCount()+1);
            userChooseTestInfo.setSubmitEndTime(new Date());//提交时间
            userChooseTestInfo.setTestScore(score);
            updateUserChooseTestInfo(userChooseTestInfo);
        }

return R.ok("成绩如下",100)
        .put("errorIds",errorList)
        .put("trueIds",trueList)
        .put("score",score)
        .put("courseTestEntityList",courseTestEntityList)
        .put("nowTime",df.format(new Date()));
    }

    /**
     * 添加用户做题记录
     */
    @PostMapping("addUserChooseTestInfo")
    public void addUserChooseTestInfo(@RequestBody UserChooseTestInfo userChooseTestInfo){
            courseTestService.addUserChooseTestInfo(userChooseTestInfo);
    }

    /**
     * 修改用户做题记录
     */
    @PostMapping("updateUserChooseTestInfo")
    public void updateUserChooseTestInfo(@RequestBody UserChooseTestInfo userChooseTestInfo){
        courseTestService.updateUserChooseTestInfo(userChooseTestInfo);
    }


    /**
     * 获取用户的做题记录
     */
    @PostMapping("getUserChooseTestInfo")
    public UserChooseTestInfo getUserChooseTestInfo(@RequestBody Map map){
        UserChooseTestInfo userChooseTestInfo = courseTestService.getUserChooseTestInfo(map);
        return userChooseTestInfo;
    }



    /**
     * 添加评论
     */
    @PostMapping("insertCourseTestComment")
    public R insertCourseTestComment(@RequestBody ChooseTestCommentEntity chooseTestCommentEntity){

        //chooseTestCommentEntity.setUsrId(Integer.valueOf(tokenService.getUserIdByToken(chooseTestCommentEntity.getToken()).toString()));
        chooseTestCommentEntity.setContent(wordFilter(chooseTestCommentEntity.getContent()));
        courseTestService.insertCourseTestComment(chooseTestCommentEntity);

        return R.ok("评论成功",100);
    }

    /**
     * 删除评论
     */
    @PostMapping("deleteCourseTestComment")
    public R deleteCourseTestComment(@RequestBody Map map){
        courseTestService.deleteCourseTestComment(map);
        return R.ok("删除评论成功",100);
    }

    /**
     * 查看评论  分页查看
     */
    @PostMapping("getCourseTestComment")
    public R getCourseTestComment(@RequestBody Map params){
        int pageNum = Integer.parseInt(params.get("pageNum").toString());
        int pageSize = Integer.parseInt(params.get("pageSize").toString());
        params.put("pageNum",pageNum);
        params.put("pageSize",pageSize);
        List courseTestCommentlist = courseTestService.getCourseTestComment(params);
        if(courseTestCommentlist.size()>0){
            ListPageUtils pageUtil = new ListPageUtils(courseTestCommentlist,pageSize);
            List list = pageUtil.getPagedList(pageNum);
            if(list.size() > 0){
                return R.ok("查询评论成功",100).put("data",list).put("nextNum",pageNum+1);
            }
            return R.ok("查询评论成功",100).put("data",list).put("nextNum",-1);
        }
        return R.ok("评论空空的哦",100).put("data",courseTestCommentlist).put("nextNum",-1);
    }
}
